package com.kgcx.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author 吴刚林
 * @date 2017/11/26
 */
@Component
public class ApplicationUtils implements ApplicationContextAware {

    private static String applicationName;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        applicationContext = ac;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> c) {
        return applicationContext.getBean(c);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }

    public static String getProperty(String name) {
        return getEnvironment().getProperty(name);
    }

    public static String getApplicationName() {
        if (StringUtils.isBlank(applicationName)) {
            applicationName = getProperty("spring.application.name");
        }
        return applicationName;
    }
}
